package server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;

public class ServerSendThread extends Thread {

	private Map<String, CopyOnWriteArrayList<SocketAddress>> sAddrs;
	private BlockingQueue<Message> toSend;
	private DatagramSocket sock;

	public static final int port = 14000;
	
	private void log(String msg) {
		Server.log(this.getName(), msg);
	}

	public ServerSendThread(Map<String, CopyOnWriteArrayList<SocketAddress>> sendTo, BlockingQueue<Message> toSend, DatagramSocket sSock) {
		super("ServSend-" + sSock.getLocalPort());
		this.sAddrs = sendTo;
		this.toSend = toSend;
		this.sock = sSock;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Message message = toSend.take();
				sendMessage(message);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void sendMessage(Message message) {
	    List<SocketAddress> sends = sAddrs.get(message.pubId);
		for (SocketAddress address : sends) {
			if (address == null)
				continue;
			
			byte[] buf = message.serialize().array();
			try {
				DatagramPacket packet = new DatagramPacket(buf, buf.length,
						address);
				sock.send(packet);
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
